#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <unordered_map>
#include <mutex>

#include "util.hpp"

// 构建索引
/*
    索引分为正排索引和倒排索引
    正排索引：根据文档序号找内容
    倒排索引：根据内容找文档号

*/
namespace ns_index
{
    struct DocInfo
    {
        std::string title;
        std::string content;
        std::string url;
        uint64_t doc_id;
    };
    struct InvertedElem
    {
        uint64_t doc_id;
        std::string word;
        int weight; // 权重
        InvertedElem():weight(0){}
    };

    typedef std::vector<InvertedElem> InvertedList; // 倒排拉链

    class Index
    {
    private:
        std::vector<DocInfo> forword_index;                           // 正排索引,下标做文档序号
        std::unordered_map<std::string, InvertedList> inverted_index; // 倒排索引,根据内容找到文档

        Index() {}
        Index(const Index &) = delete;
        Index &operator=(const Index &) = delete;

        static Index *instance;
        static std::mutex lock;

    public:
        ~Index() {}
        // 单例函数
        static Index *GetInstance()
        {
            if (nullptr == instance)
            {
                lock.lock();
                if (nullptr == instance)
                {
                    instance = new Index();
                }
            }

            lock.unlock();
            return instance;
        }
        // 根据doc_id找到找到文档内容
        DocInfo *GetForwardIndex(uint64_t doc_id)
        {
            if (doc_id >= forword_index.size())
            {
                std::cerr << "Index OUT" << std::endl;
                return nullptr;
            }
            return &forword_index[doc_id];
        }

        // 根据关键字获得倒排拉链
        InvertedList *GetInvertedList(const std::string &word)
        {
            auto iter = inverted_index.find(word);
            if (iter == inverted_index.end())
            {
                std::cerr << "have no InvertedList" << std::endl;
                return nullptr;
            }
            return &(iter->second);
        }

        // 构建正排和倒排索引
        bool BuildIndex(const std::string &input)
        {
            std::ifstream in(input, std::ios::in | std::ios::binary);
            if (!in.is_open())
            {
                std::cerr << "BuildIndex cerr" << std::endl;
                return false;
            }
            std::string  line;
            int count=0;
            while (std::getline(in, line))
            {
                // 构建正排索引
                DocInfo *doc = BuildForwardIndex(line);
                if (nullptr==doc)
                {
                    std::cerr << "Build cerr" << std::endl;
                    continue;
                }
                // 构建倒排索引
                BuildInvertedIndex(*doc);
                count++;
                if(count%50==0)
                {
                    std::cout<<"当前已构建的索引文档: "<<count<<std::endl;
                }
            }
            return true;
        }

    private:
        // std::vector<DocInfo> forword_index;   正排索引的数据结构
        DocInfo *BuildForwardIndex(const std::string &line)
        {
            // 这里已经通过getline获得一个HTML页面的内容，title,content,url,以\3为分隔符，\n位文件分隔符
            std::vector<std::string> results;
            std::string sep = "\3";
            ns_util::StringUtile::CutString(line, &results, sep);
            if (results.size() != 3)
            {
                return nullptr;
            }
            DocInfo doc;
            doc.title = results[0];
            doc.content = results[1];
            doc.url = results[2];
            doc.doc_id = forword_index.size();//

            forword_index.push_back(std::move(doc));
            return &forword_index.back();
        }
        bool BuildInvertedIndex(const DocInfo &doc)
        {
            /*
            typedef std::vector<InvertedElem> InvertedList;//倒排拉链
            std::unordered_map<std::string, InvertedList> inverted_index;//倒排索引,根据内容找到倒排拉链
            */
            struct word_cnt
            {
                int title_cnt;
                int content_cnt;
                word_cnt() : title_cnt(0), content_cnt(0) {}
            };

            std::unordered_map<std::string, word_cnt> word_map; // 词频映射表

            // 标题分词与统计词频
            std::vector<std::string> title_words;
            ns_util::JiebaUtil::CutString(doc.title, &title_words);

            for (auto s : title_words)
            {
                boost::to_lower(s);
                word_map[s].title_cnt++;
            }

            // 内容分词与统计词频
            std::vector<std::string> content_words;
            ns_util::JiebaUtil::CutString(doc.content, &content_words);

            for (auto s : content_words)
            {
                boost::to_lower(s);
                word_map[s].content_cnt++;
            }
#define X 10
#define Y 1
            for (auto &word_pair : word_map)
            {
                InvertedElem item;
                item.doc_id = doc.doc_id;
                item.word = word_pair.first;
                item.weight = X * word_pair.second.title_cnt + Y * word_pair.second.content_cnt;
                InvertedList &inverted_list = inverted_index[word_pair.first];
                inverted_list.push_back(std::move(item));
            }
            return true;
        }
    };
    Index *Index::instance = nullptr;
    std::mutex Index::lock;
}